package com.duanyf.wiki.service;

import com.duanyf.wiki.domain.Ebook;
import com.duanyf.wiki.domain.EbookExample;
import com.duanyf.wiki.domain.EbookExample.Criteria;
import com.duanyf.wiki.mapper.EbookMapper;
import com.duanyf.wiki.req.EbookQueryReq;
import com.duanyf.wiki.req.EbookSaveReq;
import com.duanyf.wiki.resp.EbookQueryResp;
import com.duanyf.wiki.resp.PageResp;
import com.duanyf.wiki.util.CopyUtil;
import com.duanyf.wiki.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @Description:
 * @Author: duanyf
 * @DateTime: 2022/9/16 0016 15:27
 */
@Service
public class EbookService {

  //使用@Autowired会报错但是运行应该没有问题
  @Resource
  private EbookMapper ebookMapper;

  @Resource
  private SnowFlake snowFlake;

    private static final Logger LOG=
          LoggerFactory.getLogger(EbookService.class);

  public PageResp<EbookQueryResp> list(EbookQueryReq req){
    EbookExample ebookExample = new EbookExample();

    //相当于where条件
    Criteria criteria = ebookExample.createCriteria();
    //动态sql
    if(!ObjectUtils.isEmpty(req.getName())){
      //不为空模糊查询
      criteria.andNameLike("%"+req.getName()+"%");
    }
    if(!ObjectUtils.isEmpty(req.getCategory2Id())){
      //不为空模糊查询
      criteria.andCategory2IdEqualTo(req.getCategory2Id());
    }

    //分页
    PageHelper.startPage(req.getPage(),req.getSize());
    List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);

    //打印总页数和总行数
    PageInfo<Ebook> pageInfo=new PageInfo<>(ebookList);
    LOG.info("总行数：{}",pageInfo.getTotal());
    LOG.info("总页数：{}",pageInfo.getPages());

    //持久层返回List<Ebook>需要转成List<EbookResp>再赋给pageResp
    List<EbookQueryResp> respList = CopyUtil.copyList(ebookList, EbookQueryResp.class);

    PageResp<EbookQueryResp> pageResp=new PageResp<>();
    pageResp.setList(respList);
    pageResp.setTotal(pageInfo.getTotal());

    return pageResp;
  }

  /**
   * 保存
   */
  public void save(EbookSaveReq req){
    Ebook ebook=CopyUtil.copy(req,Ebook.class);
    //ebook的id有值说明是更新，没有值是新增
    if (ObjectUtils.isEmpty(ebook.getId())){
      //新增
      long nextId = snowFlake.nextId();//使用雪花算法得到id
      ebook.setId(nextId);
      ebookMapper.insert(ebook);
    }else {
      //更新
      ebookMapper.updateByPrimaryKey(ebook);
    }
  }

  /**
   * 删除
   */
  public void delete(Long id){
    ebookMapper.deleteByPrimaryKey(id);
  }
}
